package utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-04
 * Time: 21:01
 */
public class DBUtils {
    private static DataSource dataSource;
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/学生选课系统";
    private static final String USER = "root";
    private static final String PassWord = "root";

    //当类被加载到JVM时候，初始化dataSource
    static{
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PassWord);
        dataSource = mysqlDataSource;
    }

    //构造方法私有化，只能通过类名调用方法
    private DBUtils(){
    }

    public static Connection getConnection() throws Exception{
        return dataSource.getConnection();
    }

    public static void close(Connection conn, Statement stat, ResultSet set) throws SQLException {
        if(set != null){
            set.close();
        }
        if(stat != null){
            stat.close();
        }
        if(conn != null){
            conn.close();
        }
    }
}
